package com.example.function;

import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Optional;

import com.azure.storage.blob.BlobClient;
import com.azure.storage.blob.BlobContainerClient;
import com.azure.storage.blob.BlobServiceClient;
import com.azure.storage.blob.BlobServiceClientBuilder;
import com.microsoft.azure.functions.ExecutionContext;
import com.microsoft.azure.functions.HttpMethod;
import com.microsoft.azure.functions.HttpRequestMessage;
import com.microsoft.azure.functions.HttpResponseMessage;
import com.microsoft.azure.functions.HttpStatus;
import com.microsoft.azure.functions.annotation.AuthorizationLevel;
import com.microsoft.azure.functions.annotation.FunctionName;
import com.microsoft.azure.functions.annotation.HttpTrigger;

public class DownloadFileFunction {
    @FunctionName("DownloadFile")
    public HttpResponseMessage run(
            @HttpTrigger(name = "req", methods = {HttpMethod.GET}, authLevel = AuthorizationLevel.FUNCTION) HttpRequestMessage<Optional<String>> request,
            final ExecutionContext context) {
        context.getLogger().info("Processing file download request.");

        try {
            // 从查询参数获取存储路径和本地路径
            String storagePath = request.getQueryParameters().get("storagePath");
            String localPath = request.getQueryParameters().get("localPath");

            if (storagePath == null || localPath == null) {
                return request.createResponseBuilder(HttpStatus.BAD_REQUEST)
                        .body("Please provide storagePath and localPath as query parameters")
                        .build();
            }

            // 从环境变量获取存储连接字符串
            String connectionString = System.getenv("AzureWebJobsStorage");
            if (connectionString == null) {
                return request.createResponseBuilder(HttpStatus.INTERNAL_SERVER_ERROR)
                        .body("Storage connection string not found in environment variables")
                        .build();
            }

            // 创建 BlobServiceClient
            BlobServiceClient blobServiceClient = new BlobServiceClientBuilder()
                    .connectionString(connectionString)
                    .buildClient();

            // 解析存储路径
            String[] pathParts = storagePath.split("/", 2);
            if (pathParts.length != 2) {
                return request.createResponseBuilder(HttpStatus.BAD_REQUEST)
                        .body("Invalid storage path format. Expected format: container/blob-path")
                        .build();
            }

            String containerName = pathParts[0];
            String blobPath = pathParts[1];

            // 获取容器客户端
            BlobContainerClient containerClient = blobServiceClient.getBlobContainerClient(containerName);
            if (!containerClient.exists()) {
                return request.createResponseBuilder(HttpStatus.NOT_FOUND)
                        .body("Container not found: " + containerName)
                        .build();
            }

            // 获取 Blob 客户端
            BlobClient blobClient = containerClient.getBlobClient(blobPath);
            if (!blobClient.exists()) {
                return request.createResponseBuilder(HttpStatus.NOT_FOUND)
                        .body("Blob not found: " + blobPath)
                        .build();
            }

            // 创建本地目录
            Path localFilePath = Paths.get(localPath);
            File localFile = localFilePath.toFile();
            localFile.getParentFile().mkdirs();

            // 下载文件
            blobClient.downloadToFile(localFilePath.toString(), true);

            return request.createResponseBuilder(HttpStatus.OK)
                    .body("File downloaded successfully to: " + localFilePath)
                    .build();

        } catch (Exception e) {
            context.getLogger().severe("Error downloading file: " + e.getMessage());
            return request.createResponseBuilder(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("Error downloading file: " + e.getMessage())
                    .build();
        }
    }
} 